/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.woundedwolf.android.tumbleweed;

import android.view.MotionEvent;
import android.view.View;
import com.woundedwolf.android.tumbleweed.elements.ACTION_TYPE;
import com.woundedwolf.android.tumbleweed.elements.ActionVector;
import com.woundedwolf.android.tumbleweed.elements.Renderable;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import android.os.SystemClock;
/**
 *
 * @author FlameDuck
 */
public abstract class AbstractGame implements android.view.View.OnTouchListener
{

	protected Engine engine;
	protected Timer updateTimer;
	protected List<ActionVector> actions;
	private long fps;

	public AbstractGame(Engine engine)
	{
		this.engine = engine;
		actions = new ArrayList<ActionVector>();
		this.engine.getView().setOnTouchListener(this);
		fps = 50;
	}

	private void setFps(long fps)
	{
		this.fps = fps;
	}

	private long getFps()
	{
		return this.fps;
	}

	public boolean onTouch(View arg0, MotionEvent arg1)
	{

		ACTION_TYPE type = null;
		switch (arg1.getAction()) {
			case MotionEvent.ACTION_DOWN:
				type = ACTION_TYPE.ACTIN_DOWN;
				break;
			case MotionEvent.ACTION_MOVE:
				type = ACTION_TYPE.ACTION_MOVE;
				break;
			case MotionEvent.ACTION_UP:
				type = ACTION_TYPE.ACTION_UP;
				break;
		}
		ActionVector av = new ActionVector((int) arg1.getX(), (int) arg1.getY(), arg1.getPressure(), arg1.getEventTime(), type);
		actions.add(av);
		return true;
	}

	protected ActionVector dequeueAction()
	{
		if (actions.isEmpty()) {
			return null;
		}
		return actions.remove(0);
	}

	protected List<ActionVector> getActions()
	{
		return actions;
	}

	protected void flushActions()
	{
		actions.clear();
	}

	protected void startGame()
	{
		renewTimer();
	}

	private void renewTimer()
	{
		long period = (long) 100 / fps;
		if (period == 0) {
			period = 1;
		}
		updateTimer = new Timer();
		updateTimer.schedule(new Updater(), 0, period);
	}

	protected void resumeGame()
	{
		renewTimer();
	}

	protected void pauseGame()
	{
		updateTimer.cancel();
		updateTimer.purge();
	}

	private class Updater extends TimerTask
	{

		@Override
		public void run()
		{
			while (true) {
				if (!engine.isReady()) {
					Thread.yield();
				} else {
					break;
				}
			}
			updateGame();
		}
	}

	public abstract void updateGame();

	public void addRenderable(Renderable renderable)
	{
		engine.addRenderable(renderable);
	}

	public void removeRenderable(Renderable renderable)
	{
		engine.removeRenderable(renderable);
	}
}
